﻿using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace DomainScan
{
    public partial class FormMain : Form
    {
        private IPAddress ipEnd;
        private IPAddress ipStart;

        public FormMain()
        {
            InitializeComponent();
        }

        private void txtSaveDir_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            folderBrowserDialog.SelectedPath = txtSaveDir.Text;
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtSaveDir.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            var regIP =
                new Regex(
                    @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
            if (!regIP.IsMatch(txtStartIP.Text))
            {
                MessageBox.Show("起始IP不合法！");
                txtStartIP.SelectAll();
                return;
            }
            if (!regIP.IsMatch(txtEndIP.Text))
            {
                MessageBox.Show("结束IP不合法！");
                txtEndIP.SelectAll();
                return;
            }

            ipStart = IPAddress.Parse(txtStartIP.Text.Trim());
            ipEnd = IPAddress.Parse(txtEndIP.Text.Trim());

            int count = ipStart.Sub(ipEnd);
            if (count < 0)
            {
                MessageBox.Show("起始IP必须小于结束IP");
                return;
            }


            txtStartIP.Enabled =
                txtEndIP.Enabled =
                    txtSaveDir.Enabled =
                        btnSearch.Enabled = false;


            txtStartIP.Enabled =
                txtEndIP.Enabled =
                    txtSaveDir.Enabled =
                        btnSearch.Enabled = true;
        }
    }
}